package sessionutil

import (
	"github.com/cihub/seelog"
	"github.com/gin-gonic/gin"
	"shop/config/constant"
	"shop/dao"
	"shop/entity"
	"shop/utils/convertutil"
	"shop/utils/jwtutil"
	"strconv"
)

func CheckLogin(userId int64) bool {
	return dao.GetRedisCli().HExists(constant.CacheKeyUserSessionMap, strconv.FormatInt(userId, 10)).Val()
}

// Logout 退出登录
func Logout(userId int64) bool {
	return dao.GetRedisCli().HDel(constant.CacheKeyUserSessionMap, strconv.FormatInt(userId, 10)).Val() == 1
}

func SetUserSession(user *entity.User) string {
	token := jwtutil.GenToken(&jwtutil.JwtClaims{
		UserId: user.Id,
		ShopId: user.ShopId,
	}, int64(3600*24*7))
	SetUserInfoCache(user)
	seelog.Debug("[add user session], token=" + token)
	return token
}

func SetUserInfoCache(user *entity.User) {
	dao.GetRedisCli().HSet(constant.CacheKeyUserSessionMap, strconv.FormatInt(user.Id, 10), convertutil.ToJsonString(user))
}

func GetUserInfoFromCache(userId int64) *entity.User {
	user := entity.User{}
	result, err := dao.GetRedisCli().HGet(constant.CacheKeyUserSessionMap, strconv.FormatInt(userId, 10)).Result()
	if err != nil {
		convertutil.ParseJson(result, &user)
	}
	return &user
}

// GetUserIdFromCtx see midware.Auth() and jwtutil.JwtClaims
func GetUserIdFromCtx(ctx *gin.Context) int64 {
	return ctx.GetInt64(constant.ParamUserId)
}

// GetShopIdFromCtx see midware.Auth() and jwtutil.JwtClaims
func GetShopIdFromCtx(ctx *gin.Context) int {
	return ctx.GetInt(constant.ParamShopId)
}
